﻿//********************************************************************************//
//创建日期：<创建日期，2016-06-23>
//创建作者：<郭登杰，guodengjie@shanghai3h.com>
//功能说明：非税接口
//********************************************************************************//
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Entity;
using BLL;
using YXYLCommon;
using System.Web;
using System.Web.SessionState;
using System.IO;
using System.Text;
using System.Data;

namespace Web.ashx.QSSFZW
{
    public class FeiShuiJK : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            int? rsno = -1;
            string rsmsg = "";
           if (context.Request["op"] == "WJXX_HQ")
            {
                int type = int.Parse(context.Request["type"]);
                List<QSZWFSWJXX_DBS> list = new DALQSZWFSJK_DBS().WJXX_HQ(type,null);
                context.Response.Write(JsonConvert.SerializeObject(list));
            }
           else if (context.Request["op"] == "MXXX_HQ")
           {
               int no=int.Parse(context.Request["no"]);
               string wjm=context.Request["wjm"];
               string jdbs=context.Request["jdbs"];
               int order = int.Parse(context.Request["order"]);
               if (no == 1)
               {
                   List<QSZWFSJCXX_DBS> list = new DALQSZWFSJK_DBS().JCXX_HQ(wjm,jdbs,order);
                   context.Response.Write(JsonConvert.SerializeObject(list));
               }
               else if(no==2)
               {
                   List<QSZWFSXZXX_DBS> list = new DALQSZWFSJK_DBS().XZXX_HQ(wjm, jdbs, order);
                   context.Response.Write(JsonConvert.SerializeObject(list));
               }
               else if (no == 3)
               {
                   List<QSZWFSSCXX_DBS> list = new DALQSZWFSJK_DBS().SCXX_HQ(wjm, jdbs, order);
                   context.Response.Write(JsonConvert.SerializeObject(list));
               }
           }
           else if (context.Request["op"] == "DR")
           {
               int a = context.Request.Files.Count;
               HttpPostedFile file = context.Request.Files[0];
               string filename = file.FileName.Substring(file.FileName.LastIndexOf("\\")+1);
               StreamReader sr = new StreamReader(file.InputStream);
               //string filename = "XZYW2017121201137002___002.txt";
               //StreamReader sr = new StreamReader("D://" + filename);
               JsonRs rs = new JsonRs();
               rs.State = false;
               //判断文件名格式
               if (filename.Substring(0, 4) != "XZYW")
               {
                   rs.Msg = "文件名格式不正确";
                   context.Response.Write(JsonConvert.SerializeObject(rs));
                   return;
               }
               //校验文件内容
               string filecontent = sr.ReadToEnd();
               //strs.Replace("\r\n","\r").Split("\r")
               string[] lines = filecontent.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
               //校验文件头
               string headstr=lines[0].Replace("-","").Replace("|","").Replace(" ","");
               headstr=headstr.Substring(0,headstr.Length-1);
               if (headstr != filename.Replace("___", "").Replace("XZYW", "").Replace("JCXX", "").Replace(".txt", ""))
               {
                   rs.Msg = "文件第1行格式不正确";
                   context.Response.Write(JsonConvert.SerializeObject(rs));
                   return;
               }
               //用于校验总金额与明细+滞纳金合计是否一致
               decimal zje = 0;
               decimal mxhj = 0;
               decimal zlj = 0;
               //校验节段头
               if (lines[1].Substring(0,4)!= "SFXX")
               {
                   rs.Msg = "文件第3行格式不正确";
                   context.Response.Write(JsonConvert.SerializeObject(rs));
                   return;
               }
               zje = decimal.Parse(lines[1].Split('|')[1]);
               //校验明细
               string[] lineitems;
               for (int i = 2; i < lines.Length; i++)
               {
                   lineitems = lines[i].Split('|');
                   if (lineitems.Length != 8)
                   {
                       rs.Msg = "文件第"+(i+1)+"行明细不正确";
                       context.Response.Write(JsonConvert.SerializeObject(rs));
                       return;
                   }
                   mxhj = mxhj + decimal.Parse(lineitems[3]);
                   zlj = zlj + decimal.Parse(lineitems[4]);
               }
              // if (zje != (mxhj + zlj))//目前不算滞纳金
               if (zje != mxhj)
               {
                   rs.Msg = "文件中总金额与明细合计金额不一致";
                   context.Response.Write(JsonConvert.SerializeObject(rs));
                   return;
               }
               //执行数据插入
               //文件信息
               string[] xxarr=lines[0].Split('|');
               QSZWFSWJXX_DBS wjxx = new QSZWFSWJXX_DBS();
               wjxx.S_FILENAME = filename.Substring(0,filename.IndexOf("."));
               wjxx.S_CAOZUOR = LoginInfo.CurrentUser.UserID.ToString();
               wjxx.I_TYPE = 1;
               wjxx.D_CREATEDATE = DbDateTime.Parse(xxarr[0]);
               wjxx.I_JIEDUANS = int.Parse(xxarr[3]);
               wjxx.S_BUMENBH = xxarr[2];
               wjxx.S_PICI = xxarr[1];
               wjxx.S_FILESTREAM = Encoding.Default.GetBytes(filecontent);
               DbCmdResult dbrs = new DALQSZWFSJK_DBS().DR_WJXX(wjxx);
               if (!dbrs.IsSuccess)
               {
                   rs.Msg = dbrs.ReturnMsg;
                   context.Response.Write(JsonConvert.SerializeObject(rs));
                   return;
               }
               //明细信息
               for (int i = 2; i < lines.Length; i++)
               {
                   QSZWFSXZXX_DBS mxxx = new QSZWFSXZXX_DBS();
                   mxxx.SFILENAME = wjxx.S_FILENAME;
                   xxarr = lines[i].Split('|');
                   mxxx.SID = xxarr[0];
                   mxxx.SBEGINID=xxarr[1];
                   mxxx.SBANKCODE=xxarr[2];
                   mxxx.NMONEY = DbDecimal.Parse(xxarr[3]);
                   mxxx.NLATEFEE = DbDecimal.Parse(xxarr[4]);
                   mxxx.DTREGDATE = DbDateTime.Parse(xxarr[5]);
                   mxxx.SCASHIER = xxarr[6];
                   mxxx.DTCHECKBILL = DbDateTime.Parse(xxarr[7]);
                   mxxx.ILISTNO = DbInt.Parse(i - 1);
                   dbrs = new DALQSZWFSJK_DBS().DR_XZXX(mxxx,LoginInfo.CurrentUser.UserID.ToString());
                   if (!dbrs.IsSuccess)
                   {
                       rs.Msg = dbrs.ReturnMsg;
                       context.Response.Write(JsonConvert.SerializeObject(rs));
                       return;
                   }
               }
               rs.State = true;
               rs.Msg = "导入成功";
               rs.Data1 = wjxx.S_FILENAME;
               context.Response.Write(JsonConvert.SerializeObject(rs));
           }
           else if (context.Request["op"] == "TQ")
           {
               string filename = context.Request["filename"];
               int type = int.Parse(context.Request["type"]);
               //context.Response.ContentEncoding = System.Text.Encoding.UTF8;
               context.Response.ContentEncoding = Encoding.GetEncoding("gb2312");
               context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename+".txt");
               context.Response.ContentType = "text/plain;charset=gb2312";
               //context.Response.ContentType = "text/plain;charset=UTF-8";
               List<QSZWFSWJXX_DBS> list = new DALQSZWFSJK_DBS().WJXX_HQ(type, filename);
               QSZWFSWJXX_DBS obj = list[0];
               string filestr=System.Text.Encoding.Default.GetString(obj.S_FILESTREAM);
               context.Response.Write(filestr);
           }
            else if (context.Request["op"] == "QX")
           {
               string filename = context.Request["filename"];
               int type = int.Parse(context.Request["type"]);
               DbCmdResult dbrs = new DALQSZWFSJK_DBS().QX_WJXX(type, filename, LoginInfo.CurrentUser.Account);
               context.Response.Write(JsonConvert.SerializeObject(new JsonRs(dbrs.IsSuccess, dbrs.ReturnMsg, null)));
           }
           else if (context.Request["op"] == "SC")
           {
               string filename = "";
               string rsnot = "-1";               
               try
               {
                   DataSet ds = SearchSpHelper.P_DBSZW_FEISHUISCXXSC(out filename, out rsnot, out rsmsg);
                   if (rsnot == "1" && ds.Tables.Count > 0)
                   {
                       StringBuilder sb = new StringBuilder();
                       foreach (DataRow item in ds.Tables[0].Rows)
                       {
                           if (Convert.ToString(item[0]) == "0" || Convert.ToString(item[0])=="2")
                           {
                               sb.AppendLine();
                           }
                           sb.AppendLine(item[1].ToString());                           
                       }
                       //context.Response.ContentEncoding = System.Text.Encoding.UTF8;
                       context.Response.ContentEncoding = Encoding.GetEncoding("gb2312");
                       context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename + ".txt");
                       //context.Response.ContentType = "text/plain;charset=UTF-8";
                       context.Response.ContentType = "text/plain;charset=gb2312";
                       //更新数据库中文件流
                       string content = sb.ToString();
                       QSZWFSWJXX_DBS wjxx = new QSZWFSWJXX_DBS();
                       wjxx.S_FILENAME = filename;
                       wjxx.S_FILESTREAM = Encoding.Default.GetBytes(content);
                       new DALQSZWFSJK_DBS().UPDATE_WJXX(wjxx);
                       context.Response.Write(sb.ToString());
                   }
                   else
                   {
                       context.Response.Write(JsonConvert.SerializeObject(new JsonRs(false, rsmsg, null)));
                   }
               }
               catch (Exception ex)
               {
                   rsnot = "-1";
                   rsmsg = "系统异常";
                   context.Response.Write(JsonConvert.SerializeObject(new JsonRs(false, rsmsg, null)));
               }
              
           }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}